<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ProductSku;
use App\Models\SpecificationItem;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Callout;
use Encore\Admin\Widgets\Form as WidgetsForm;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class ProductSkusController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content, Request $request)
    {
        \Cache::forget('createskubypid');
        \Cache::add('createskubypid', $request->pid, 15);
        return $content
            ->header('产品sku')
            ->body($this->grid($request->pid));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        $pid = \Cache::get('createskubypid');
        \Cache::forget('createskubypid');
        return redirect('/admin/product_skus/edit_sku?pid=' . $pid);
    }

    public function edit($id, Content $content)
    {
        $pid = \Cache::get('createskubypid');
        \Cache::forget('createskubypid');
        return redirect('/admin/product_skus/edit_sku?pid=' . $pid);
    }
    public function form()
    {
        $form = new Form(new ProductSku);
        $form->decimal('price');
        $form->number('stock');
        $form->saved(function (Form $form) {
            $product = Product::find($form->model()->product_id);
            //设置商品价格和库存为sku里面最少那个
            $product->price = collect($product->skus)->min('price') ?: 0;
            $product->stock = collect($product->skus)->min('stock') ?: 0;
            $product->save();
        });
        $form->deleted(function (Form $form) {
        });
        return $form;
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid($pid)
    {
        $grid = new Grid(new ProductSku);
        $grid->model()->where('product_id', $pid);
        $grid->id('Id');
        $grid->column('product.title', '所属商品');
        $grid->title('sku标题');
        // $grid->description('Description','描述');
        $grid->price('价格')->editable();
        $grid->stock('库存')->editable();
        $grid->actions(function ($actions) {
            // 不展示 Laravel-Admin 默认的查看按钮
            $actions->disableView();
            $actions->disableEdit();
        });

        $grid->disableFilter();
        $grid->disableExport();
        return $grid;
    }

    public function editSku(Request $request, Content $content)
    {
        return $content
            ->header('编辑商品sku')
            ->row($this->skuForm($request->pid))
            ->row($this->skuInfo($request->pid));
    }
    protected function skuInfo($product_id)
    {
        $product = Product::with('skus', 'category.specs.items')->find($product_id);
        if ($product) {
            if (count($product->skus)) {
                $headers = ['sku标题'];
                $rows = [];
                foreach ($product->skus as $sku) {
                    $rows[][] = $sku->title;
                }
                $table = new Table($headers, $rows);
                return (new Box('已添加的sku（请核对，重复添加会导致保存失败）', $table))->style('danger')->solid();
            }
            return '';
        }
    }
    protected function skuForm($product_id)
    {
        $product = Product::with('skus', 'category.specs.items')->find($product_id);
        if ($product) {
            // $form = new Form(new Product);
            $form = new WidgetsForm();
            $form->disablePjax();
            foreach ($product->category->specs as $spec) {
                $f = $form->checkbox($spec->name, $spec->title);
                // $f->options($spec->items()->pluck('item', 'item'));
                $f->options($spec->items()->pluck('item', 'id'));
            }
            $form->hidden('product_id')->default($product_id);
            // $form->action('/admin/products/'.$product_id.'/edit_sku');
            $box = new Box('选择商品规格值', $form);
            return $box;
        } else {
            return new Callout('商品信息获取失败,返回重试');
        }
    }

    public function store(Request $request)
    {
        $product = Product::with('category.specs')->find($request->product_id);
        if ($product) {
            $extra = [];
            $specinfo = [];
            foreach ($product->category->specs as $spec) {
                $extra[] = array_filter($request->input($spec->name));
            }
            if ($extra && count($extra) == count($product->category->specs)) {
                $skuitemids = $this->genarateSku($extra);
                foreach ($skuitemids as $itemids) {
                    $id_array = explode(',', $itemids);
                    $spec_items = [];
                    $title = '';
                    foreach ($id_array as $itemid) {
                        $spec_item = SpecificationItem::find($itemid);
                        $title = $title . $spec_item->item;
                        $spec_items[$spec_item->spec->name] = $spec_item;
                    }
                    $res = $product->skus()->create([
                        'title' => $title,
                        'spec_items' => json_encode($spec_items),
                        'price' => 0.00,
                        'stock' => 0,
                    ]);
                }
                return redirect('/admin/product_skus?pid=' . $request->product_id);
            } else {
                $error = new MessageBag([
                    'title' => '提示...',
                    'message' => '请选择所有规格....',
                ]);
                return back()->with(compact('error'));
            }
        } else {
            $error = new MessageBag([
                'title' => '提示...',
                'message' => '商品信息获取失败,返回重试....',
            ]);
            return back()->with(compact('error'));
        }
    }
    //笛卡尔积计算sku组合
    public function genarateSku($sets)
    {
        // 保存结果
        $result = array();
        // 循环遍历集合数据
        for ($i = 0, $count = count($sets); $i < $count - 1; $i++) {
            // 初始化
            if ($i == 0) {
                $result = $sets[$i];
            }
            // 保存临时数据
            $tmp = array();
            // 结果与下一个集合计算笛卡尔积
            foreach ($result as $res) {
                foreach ($sets[$i + 1] as $set) {
                    $tmp[] = $res . ',' . $set;
                }
            }
            // 将笛卡尔积写入结果
            $result = $tmp;
        }
        return $result;
    }
}
